import threading

from pk.WindowManager import WindowManager


class Yabiao:
    def __init__(self, setupui):
        self.setupUi = setupui
        self.threads = []  # 用于存储所有挖图线程
        self.stop_flag = threading.Event()

    def btn_command(self):
        if any(thread.is_alive() for thread in self.threads):
            self.stop_flag.set()
            for thread in self.threads:
                thread.join(timeout=1)  # 增加超时时间
            self.threads = []  # 清空线程列表
            self.setupUi.btn_yabiao.config(text="自动押镖")
            self.setupUi.add_log("停止自动押镖")
        else:
            if self.setupUi.selectHwnd:
                self.stop_flag.clear()
                for hwnd in self.setupUi.selectHwnd:
                    thread = threading.Thread(target=self.run_command, args=(hwnd,))
                    thread.daemon = True
                    thread.start()
                    self.threads.append(thread)
                self.setupUi.btn_yabiao.config(text="停止押镖")
            else:
                self.setupUi.add_log("未选择窗口，无法开始自动押镖")
            return

    def run_command(self, hwnd):
        try:
            for x in range(3):
                if self.stop_flag.is_set():
                    break

                WindowManager.sleep(0.3)

                while not self.stop_flag.is_set():
                    f = WindowManager.findImgAndClick(hwnd, "image/yabiao/yaputongbiao.png")
                    if f:
                        break
                    WindowManager.sleep(1)
                if x != 0:
                    self.setupUi.add_log(f"第 {x} 次押镖结束")

                self.setupUi.add_log(f"第 {x + 1} 次押镖开始")

                while not self.stop_flag.is_set():
                    WindowManager.sleep(0.3)
                    f = WindowManager.findImgAndDubleClick(hwnd, "image/yabiao/queren.png")
                    if f:
                        break

                # 拆分长时间休眠，增加状态检查
                total_sleep_time = 50
                while total_sleep_time > 0 and not self.stop_flag.is_set():
                    WindowManager.sleep(0.6)
                    total_sleep_time -= 1

            self.stop_flag.clear()
            self.threads = []  # 清空线程列表
            self.setupUi.btn_yabiao.config(text="自动押镖")
            self.setupUi.add_log("停止自动押镖")
        except Exception as e:
            print(f"押镖线程出错: {e}")
